import { useEffect, useState } from "react";
import {
    Form, Input, Button, Modal, Space, Popconfirm, Select, Radio, Switch,
    InputNumber,Flex,DatePicker
} from "antd";
import dayjs from 'dayjs';

export default function MyForm(props:any) {
    let [form] = Form.useForm();
    const [formBody, setFormBody] = useState<any[]>([]);

    function getChild(item: any): any {
        switch (item.itemType) {
            case "input":
                return  <Input allowClear/>;
            case "select":
                return <Select allowClear options={item.dict}/>;
            case "radio":
                return <Radio.Group>
                        {item.dict.map((dictItem: any) => (
                            <Radio key={dictItem.value} value={dictItem.value}>{dictItem.label}</Radio>
                        ))}   
                       </Radio.Group>;
            case "switch":
                return <Switch/>;
            case "inputNumber":
                return <InputNumber style={{ width: 250 }}/>;
            case "inputText":
                return <Input.TextArea/>
            case "datePicker":
                return <DatePicker style={{ width: 250 }}/>;
            default:
            return null;
        }
    }
    useEffect(() => {
        let formData = {...props.formData}
        props.formItem.map((item:any) => {
            if (item.itemType === 'datePicker') {
                formData[item.name] = dayjs(formData[item.name]).valueOf()
            } else {
                formData[item.name] = formData[item.name]
            }
        })
        // 给表单赋值
        form.setFieldsValue(formData)
    });

    useEffect(() => {
        let Child = []
        props.formItem.map((item) => {
            Child.push(getChild(item))
            setFormBody(Child)
        })
    }, []); 
    
    return (
        <div>
            <Form form={form} labelWrap>
                <Flex wrap gap="small">
                    {props.formItem.map((item, index) => (
                        <Form.Item
                            key={item.name}
                            {...item}
                            getValueProps={item.getValueProps ? (value) => ({ value: value && dayjs(Number(value)) }) : undefined}
                            normalize={item.normalize ? (value) => value && `${dayjs(value).valueOf()}` : undefined}
                            style={{ width: '300px' }}
                        >
                            {formBody[index]}
                        </Form.Item>
                    ))}
                </Flex>
            </Form>
            
        </div>
    )
    
}